package com.eportal.action.background;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TKeysProlong;
import com.eportal.domain.TUsers;
import com.eportal.domain.User;
import com.eportal.domain.UsersApply;
import com.eportal.service.TKeysProlongService;
import com.eportal.service.TUsersService;
import com.eportal.util.CityUtil;
import com.eportal.util.DateUtils;
import com.eportal.util.HomePageConfig;
import com.eportal.util.UploadUtil;
import com.framework.excelTools.ExcelUtil;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 住户管理
 * @author chencheng
 *
 */
public class TUsersAction extends BaseAction implements ModelDriven<TUsers> {

    /**
	 * @author chencheng
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(TUsersAction.class.getName());

    private Map<String, Object> result = new HashMap<String, Object>();
    public static String PATH = "/upload/批量用户导入模板.xls";
    @Autowired
    private TUsersService tUsersService;
    @Autowired
    private TKeysProlongService tKeysProlongService;

	/**
     * 住户管理
     */
    public String listView() {
    	getRequest().setAttribute("communityId", getRequest().getParameter("communityId"));
    	getRequest().setAttribute("agtCode", getRequest().getParameter("agtCode"));
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 1) {
    		getRequest().setAttribute("agtCodeA", getRequest().getParameter("agtCode"));
    		getRequest().setAttribute("communityIdA", getRequest().getParameter("communityId"));
		}else{
			getRequest().setAttribute("agtCodeA", "");
    		getRequest().setAttribute("communityIdA", "");
		}
    	getRequest().setAttribute("userRole", userRole);
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	getRequest().setAttribute("rLevel", user.getrLevel());
    	String homePageConfig = HomePageConfig.YONGHUGL;
    	String[] str = homePageConfig.split(",");
		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
        return SUCCESS;
    }
    
    /**
     * 住户列表
     */
    public void page() throws Exception {
        JqGridPager jqGridPager = new JqGridPager();
        String agtCode = getRequest().getParameter("agtCode");
    	String communityId = getRequest().getParameter("communityId");
    	String areaCode = getRequest().getParameter("areaCode");
    	String auName = getRequest().getParameter("auName");
    	String nickName = getRequest().getParameter("nickName");
    	String auTel = getRequest().getParameter("auTel");
    	String cBuildingId = getRequest().getParameter("cBuildingId");
    	String unitId = getRequest().getParameter("unitId");
    	String roomNo = getRequest().getParameter("roomNo");
    	String utype = getRequest().getParameter("utype");
    	
    	StringBuilder where = new StringBuilder(" t.status=1 ");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	
    	if (userRole == 1 || userRole == 2 || userRole == 21) {
    		if (StringUtils.isNotBlank(agtCode)) {
    			where.append(" and c.agtCode ='");
    			where.append(agtCode);
    			where.append("'");
            }
    		if (StringUtils.isNotBlank(communityId)) {
                where.append(" and  t.communityId = '");
                where.append(communityId);
                where.append("'");
            }
    		if (userRole == 21) {
    			where.append(" and a.sysoptId =");
    			where.append(user.getSid());
			}
    	}
    	if (userRole == 3 || userRole == 4) {
    		where.append(" and c.agtCode ='");
    		where.append(user.getAgtCode());
    		where.append("'");
    		if (StringUtils.isNotBlank(communityId)) {
                where.append(" and  t.communityId = '");
                where.append(communityId);
                where.append("'");
            }
    	}
    	if (userRole == 5 || userRole == 6) {
    		where.append(" and t.communityId ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    	}
    	
    	if (StringUtils.isNotBlank(areaCode)) {
    		where.append(" and  substr(c.areaCode,1,");
        	if(CityUtil.isMunicipalities(areaCode)){//直辖市
        		where.append("2) = '");
        		where.append(areaCode.substring(0, 2));
        		where.append("'");
        	}else{									
        		where.append("4) = '");
        		where.append(areaCode.substring(0, 4));
        		where.append("'");
        	}
        }
    	if (!StringUtils.isBlank(auName)) {
    		where.append(" and u.auname like '%");
    		where.append(auName);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(nickName)) {
    		where.append(" and u.nickName like '%");
    		where.append(nickName);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(auTel)) {
    		where.append(" and u.tel like '%");
    		where.append(auTel);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(cBuildingId)) {
    		where.append(" and cbu.sid = '");
    		where.append(cBuildingId);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(unitId)) {
    		where.append(" and cin.sid = '");
    		where.append(unitId);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(roomNo)) {
    		where.append(" and t2.room_no = '");
    		where.append(roomNo);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(utype)) {
    		where.append(" and t1.utype = '");
    		where.append(utype);
    		where.append("'");
    	}

    	jqGridPager.setWhere(where.toString());
        setPage(getRequest(), jqGridPager);
        List<TUsers> tUsers = tUsersService.list(jqGridPager);
        jqGridQueryMap(TUsers.class, getRequest(), tUsers, getResponse(), jqGridPager);
    }
    
    /**
     * 用户list用于选择
     */
    public void list() throws Exception {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder();
    	if (userRole == 21) {
    		where.append("select u.sid,u.userId,u.auName from t04_users_community uc left join t04_users u on u.userId = uc.userId left join t02_agtent a on u.agtCode=a.agtCode");
    		where.append(" where uc.status=1 and a.sysoptId=");
    		where.append(user.getSid());
		}else{
			where.append("select u.sid,u.userId,u.auName from t04_users_community uc, t04_users u");
			//内部账号
			where.append(" where uc.status=1 and u.userId = uc.userId and u.agtCode ='");
			where.append(user.getAgtCode());
			where.append("' ");
			where.append("and uc.communityId ='");
			where.append(user.getCommunityId());
			where.append("' ");
		}
		List<Map<String, String>> tUsers = tUsersService.list(where.toString());
        responseBody(tUsers);
    }
    
    /**
     * 住户增加
     */
    public String addView() {
        return SUCCESS;
    }
    
    /**
     * 住户新增保存
     */
    public void add(){
    	TUsers tUser = getModel();
    	result = tUsersService.addMethod(tUser);
        responseBody(result);
    }

    /**
     * 住户审核
     */
    public String approve(){
    	String sid = getRequest().getParameter("sid");
    	List<Map<String, String>> list = tUsersService.getApplyDetail(sid);
    	getRequest().setAttribute("auname", list.get(0).get("auname"));
    	getRequest().setAttribute("room", list.get(0).get("room"));
    	getRequest().setAttribute("tel", list.get(0).get("tel"));
    	getRequest().setAttribute("ctime", list.get(0).get("ctime"));
    	getRequest().setAttribute("comm", list.get(0).get("comm"));   	
    	return SUCCESS;
    }
    /**
     * 住户修改
     */
    public String editView() {
    	TUsers tUser = tUsersService.get(getModel().getSid());
        getRequest().setAttribute("tUser", tUser);
        return SUCCESS;
    }
    
    /**
     * 住户修改保存
     */
    public void update(){
    	TUsers tUser = getModel();
    	result = tUsersService.updateMethod(tUser);
        responseBody(result);
    }
    
    /**
     * 删除
     */
    public void delete(){
    	String param_ids = getRequest().getParameter("ids");
    	result = tUsersService.deleteMethod(param_ids);
        responseBody(result);
    }
    
    /**
     * 住户审核页面
     */
    public String auditListView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 1) {
    		getRequest().setAttribute("agtCode", getRequest().getParameter("agtCode"));
    		getRequest().setAttribute("communityId", getRequest().getParameter("communityId"));
    	}else{
    		getRequest().setAttribute("communityId", "");
    		getRequest().setAttribute("agtCode", "");
    		
    	}
    	return SUCCESS;
    }
    
    
    /**
     * 审核住户列表
     */
    public void auditList() throws Exception {
        JqGridPager jqGridPager = new JqGridPager();
        Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String communityId = getRequest().getParameter("communityId");
   	 	if (StringUtils.isBlank(communityId)) {
   	 		communityId = user.getCommunityId();
		}
   	 	String agtCode = getRequest().getParameter("agtCode");
   	 	if (StringUtils.isBlank(agtCode)) {
   	 		agtCode = user.getAgtCode();
		}
//    	StringBuilder where = new StringBuilder(" 1=1 ");
//        where.append(" and a.agtCode = '");
//        where.append(agtCode);
//        where.append("'");
//		where.append(" and a.communityId = '");
//		where.append(communityId);
//		where.append("'");
//    	jqGridPager.setWhere(where.toString());
        setPage(getRequest(), jqGridPager);
        jqGridPager.setSord(null);
        jqGridPager.setSidx(null);
        List<UsersApply> usersApplys = tUsersService.userApplyList(jqGridPager,agtCode,communityId);
        jqGridQueryMap(TUsers.class, getRequest(), usersApplys, getResponse(), jqGridPager);
    }
    
    /**
     * 住户审核
     */
    public void audit(){
    	String sid = getRequest().getParameter("sid");
    	String status = getRequest().getParameter("status");
    	String pubId = getRequest().getParameter("pubId");
    	String prvId = getRequest().getParameter("prvId");
    	String validity = getRequest().getParameter("validity");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
     	String communityId = getRequest().getParameter("communityId");
     	String roomStatus = getRequest().getParameter("roomStatus");//房屋状态
     	String flag = getRequest().getParameter("flag");//是否默认配发钥匙 为1表示默认
    	 	if (StringUtils.isBlank(communityId)) {
    	 		communityId = user.getCommunityId();
 		}
	 	String agtCode = getRequest().getParameter("agtCode");
	 	if (StringUtils.isBlank(agtCode)) {
	 		agtCode = user.getAgtCode();
 		}
    	try {
			result = tUsersService.auditMethod(sid,status,roomStatus,flag,pubId,prvId,validity,agtCode,communityId);
		} catch (Exception e) {
			 result.put("code", 0);
             result.put("msg", "操作失败");
             log.error(this, e);
		}finally{
        responseBody(result);
		}
    }
    
    /**
     * 钥匙选择
     * @Description: 授权钥匙
     * @return
     */
    public String selectKeysView(){
    	String sid = getRequest().getParameter("sid");
    	String roomStatus = getRequest().getParameter("roomStatus");
    	getRequest().setAttribute("roomStatus", roomStatus);
    	getRequest().setAttribute("sid", sid);
    	getRequest().setAttribute("communityId", getRequest().getParameter("communityId"));
    	getRequest().setAttribute("agtCode", getRequest().getParameter("agtCode"));
    	return SUCCESS;
    }
    
    /**
     * 授权钥匙列表
     */
    public void selectKeysList() throws Exception {
        JqGridPager jqGridPager = new JqGridPager();
        Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	
    	StringBuilder where = new StringBuilder(" 1=1 ");
        where.append(" and agtCode = '");
        where.append(user.getAgtCode());
        where.append("'");
		where.append(" and communityId = '");
		where.append(user.getCommunityId());
		where.append("'");
		where.append("status = '0'");
    	jqGridPager.setWhere(where.toString());
        setPage(getRequest(), jqGridPager);
        List<TUsers> tUsers = tUsersService.list(jqGridPager);
        jqGridQueryMap(TUsers.class, getRequest(), tUsers, getResponse(), jqGridPager);
    }
    
    /**
     * 预发钥匙页面
     * @Description: 授权钥匙
     * @return
     */
    public String authorizeKeysView(){
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 1) {
    		getRequest().setAttribute("agtCode", getRequest().getParameter("agtCode"));
    		getRequest().setAttribute("communityId", getRequest().getParameter("communityId"));
    	}else{
    		getRequest().setAttribute("communityId", "");
    		getRequest().setAttribute("agtCode", "");
    		
    	}
    	return SUCCESS;
    }
    
    /**
     * 预发钥匙列表
     * @throws Exception
     */
    public void authorizeKeysList() throws Exception {
        List<Map<String, String>> listmap = new ArrayList<Map<String,String>>();
        Map<String, String> map;
        for (int i = 0; i < 10; i++) {
        	map =  new HashMap<String, String>();
        	map.put("TEL", "");
        	map.put("NAME", "");
        	listmap.add(map);
		}
        responseBody(listmap);
    }
    
    /**
     * 批量新增
     * @throws Exception
     */
    public void batchUser() throws Exception {
    	try {
    		JqGridPager jqGridPager = new JqGridPager();
    		File file = getUpload();
//    	String fileName = getUploadFileName();
    		FileInputStream fis = null;  
    		fis = new FileInputStream(file); 
    		String sheetname  = "用户批量导入";
    		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
    		map.put("手机号", "tel");
    		map.put("姓名", "name");
    		String[] uniqueFields = {"手机号","姓名"};
    		List<User> list= ExcelUtil.excelToList(fis,sheetname,User.class,map,uniqueFields);
    		List<Map<String, String>> listmap = new ArrayList<Map<String,String>>();
    		Map<String, String> usermap;
    		for (int i = 0; i < list.size(); i++) {
    			usermap =  new HashMap<String, String>();
    			usermap.put("TEL", list.get(i).getTel());
    			usermap.put("NAME", list.get(i).getName());
    			listmap.add(usermap);
    		}
    		responseBody(listmap);
		} catch (Exception e) {
			 result.put("code", 0);
             result.put("msg", "excel导入失败，查看格式是否正确");
             responseBody(result);
             log.error(this, e);
		}
    }
    /**
     * 下载模板
     * @throws Exception
     */
    public void download() throws Exception {
    	String path = File.separator+"upload"+File.separator;
    	String destDir = ServletActionContext.getRequest().getServletContext().getRealPath(path);
    	String fileName = "model.xls";
    	UploadUtil.download(destDir,fileName,getResponse());
    }
    /**
     * 
     * 
     * data，用户信息：手机号;姓名
     */
    public void authorizeKeys(){
    	try{
    		String data = getRequest().getParameter("data");
        	String pubId = getRequest().getParameter("pubId");
        	String prvId = getRequest().getParameter("prvId");
        	String validity = getRequest().getParameter("validity");
        	Sysopt  user= (Sysopt)getSession().getAttribute("user");
        	String communityId = getRequest().getParameter("communityId");
        	if (StringUtils.isBlank(communityId)) {
       	 		communityId = user.getCommunityId();
    		}
        	String agtCode = getRequest().getParameter("agtCode");
        	if (StringUtils.isBlank(agtCode)) {
        		agtCode = user.getAgtCode();
    		}
        	String startTime = getRequest().getParameter("startTime");
        	Date startTime_ = new Date(); 
        	startTime_ = DateUtils.stringToDate(startTime,"yyyyMMddHHmmss");
        	result = tUsersService.authorizeKeysMethod(data,pubId,prvId,DateUtils.stringToDate(validity,"yyyy-MM-dd"),communityId,agtCode,null,startTime_);
            responseBody(result);
    		try{
    			String prolong = getRequest().getParameter("prolong");
            	if("1".equals(prolong)){//延期钥匙
            		String prolongId = getRequest().getParameter("prolongId");
            		TKeysProlong tKeysProlong = tKeysProlongService.get(Long.valueOf(prolongId));
            		tKeysProlong.setPstate("2");;//修改状态为已处理
            		tKeysProlongService.update(tKeysProlong);
            	}
            	
    		}catch(Exception e){
        		log.error(this, e);
        	}
    	
    	}catch(Exception e){
    		log.error(this, e);
    	}
    	
    }
    
    /**
     * 发放钥匙，目前供app调用
     */
    public void authorizeKeysV2(){
    	try{
    		String tel = getRequest().getParameter("tel");
    		String cname = getRequest().getParameter("cname");
        	String pubId = getRequest().getParameter("lock_id");
        	String validity = getRequest().getParameter("endTime_");
        	Sysopt  user= (Sysopt)getSession().getAttribute("user");
       	 	String	communityId = user.getCommunityId();
        	String agtCode = user.getAgtCode();
        	String startTime = getRequest().getParameter("startTime_");
        	result = tUsersService.authorizeKeysMethod(tel+";"+cname,pubId,null,new Date(Long.valueOf(validity)),communityId,agtCode,null,new Date(Long.valueOf(startTime)));
            responseBody(result);
    		try{
    			String prolong = getRequest().getParameter("prolong");
            	if("1".equals(prolong)){//延期钥匙
            		String prolongId = getRequest().getParameter("prolongId");
            		TKeysProlong tKeysProlong = tKeysProlongService.get(Long.valueOf(prolongId));
            		tKeysProlong.setPstate("2");;//修改状态为已处理
            		tKeysProlongService.update(tKeysProlong);
            	}
            	
    		}catch(Exception e){
        		log.error(this, e);
        	}
    	
    	}catch(Exception e){
    		log.error(this, e);
    	}
    	
    }
    
    /**
     * 锁厂发放测试钥匙
     */
    public void addTestKey(){
    	String tel = getRequest().getParameter("tel");
    	String userName = getRequest().getParameter("userName");
    	String sid = getRequest().getParameter("sid");
    	String validity = getRequest().getParameter("validity");
    	
    	result = tUsersService.addTestKeyMethod(sid,tel,userName,validity);
    	
        responseBody(result);
    }
    
    public void addKey(){
    	String tel = getRequest().getParameter("tel");
    	String userName = getRequest().getParameter("userName");
    	String sid = getRequest().getParameter("sid");
    	String validity = getRequest().getParameter("validity");
    	
    	result = tUsersService.addTestKeyMethod(sid,tel,userName,validity);
    	
        responseBody(result);
    }
    
    /**
     * 用户详情页面
     * @return
     */
    public String userDetail(){
    	String userId = getRequest().getParameter("userId");
    	if(StringUtils.isBlank(userId)){
    		return "error";
    	}
    	if (!tUsersService.haveRole(userId)) {
    		return "error";
		}
    	getRequest().setAttribute("userId", userId);
  	  	return SUCCESS;
    }
    /**
     * 用户详情页面
     * @return
     */
    public String userDetail2(){
    	String userId = getRequest().getParameter("userId");
    	if(StringUtils.isBlank(userId)){
    		return "error";
    	}
    	if (!tUsersService.haveRole(userId)) {
    		return "error";
    	}
    	getRequest().setAttribute("userId", userId);
    	return SUCCESS;
    }
    
    /**
     * 用户详情查询
     */
    public void userDetailQuery(){
    	String userId = getRequest().getParameter("userId");
    	result = tUsersService.userDetailQuery(userId);
        responseBody(result);
    }
   

	private TUsers tUser = new TUsers();

    @Override
    public TUsers getModel() {
        return tUser;
    }
}
